package com.getword.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.getword.security.core.properties.LoginType;
import com.getword.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component("vstudyAuthenticationSuccessHandler")
public class VstudyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    // 请求缓存
//    private RequestCache requestCache = new HttpSessionRequestCache();
    //工具类, 将对象转成json
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties; //获取配置信息

    // 登录成功后调用
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功");
        if(LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
//            SavedRequest savedRequest = requestCache.getRequest(request, response);
//            String targetUrl = savedRequest.getRedirectUrl();
//            SimpleResponse result = new SimpleResponse(authentication);
//            result.setRedirectUrl(targetUrl);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else{
            // 调用父类方法，完成重定向跳转
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
